import React, { useState, useEffect } from 'react'
import { useHistory } from 'react-router-dom'
import { Table, Image, Row, Col, Button, message } from 'antd'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import { getProducts, addProduct, delProduct } from '@/api/product'
import { typeProduct } from '@/types/product'
import { $confirm } from '@/register/globalFun'
import './index.scss'

const pageSize = 5
const ProductManage = () => {
  const history = useHistory()
  const [current, setCurrent] = useState<number>(1)
  const [total, setTotal] = useState<number>(0)
  const [products, setProducts] = useState<typeProduct[]>([])

  useEffect(() => {
    loadProducts(1)
  }, [])

  /**
   * 加载项目列表
   */
  const loadProducts = async(pageNum = current) => {
    const res = await getProducts({
      pageNum,
      pageSize
    })

    setProducts(res.data.products)
    setTotal(res.data.total)
    setCurrent(pageNum)
  }

  const onclickDelProduct = (productId:string) => {
    $confirm('确认删除该商品？', async() => {
      await delProduct(productId)
      message.info('删除成功')
      loadProducts()
    })
  }

  const onclickAddProduct = async() => {
    await addProduct()
    message.success('添加成功')
    loadProducts()
  }

  const columns = [
    {
      title: '图片',
      dataIndex: 'image',
      render: (text:string, record:typeProduct) => (
        <Image
          preview
          src={record.image}
          width="50px"
        />
      )
    },
    {
      title: '类别',
      dataIndex: 'category',
    },
    {
      title: '商品名',
      dataIndex: 'name',
    },
    {
      title: '价格',
      dataIndex: 'price',
    },
    {
      title: '库存',
      dataIndex: 'countInStock',
    },
    {
      title: '评分',
      dataIndex: 'rating',
    },
    {
      title: '操作',
      key: 'control',
      render: (text:string, record:typeProduct) => (
        <Row gutter={20}>
          <Col>
            <Button
              icon={<EditOutlined />}
              onClick={() => { history.push(`/admin/product-edit/${ record._id }`) }}
              shape="circle"
            />
          </Col>
          <Col>
            <Button
              danger
              icon={<DeleteOutlined />}
              onClick={() => onclickDelProduct(record._id)}
              shape="circle"
            />
          </Col>
        </Row>
      )
    },
  ]

  return products && (
    <div className="products-manage">
      <Row>
        <Col flex={1}>
          <h1>商品管理</h1>
        </Col>
        <Col>
          <Button
            onClick={onclickAddProduct}
            type="primary"
          >
            添加新商品
          </Button>
        </Col>
      </Row>
      <Table
        columns={columns}
        dataSource={products}
        pagination={{
          position: ['bottomRight'],
          pageSize,
          current,
          total,
          onChange: (current) => {
            loadProducts(current)
          }
        }}
        rowKey={(record:typeProduct) => record._id || ''}
      />
    </div>
  )
}

export default ProductManage
